package book.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 实现一个同时只能有两个线程访问的锁
 * @author tuyou_cd
 * @date 2021/2/13 22:27
 */
public class TwiceLock implements Lock {

    Sync sync = new Sync();

    private class Sync extends AbstractQueuedSynchronizer {

        Sync() {
            setState(2);
        }

        @Override
        protected int tryAcquireShared(int arg) {
            int state = getState();
            int result = state - arg;
            if (result >= 0 && compareAndSetState(state, result)) {
                return result;
            }
            return -1;
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            int state = getState();
            int result = state + arg;
            return compareAndSetState(state, result);
        }

        @Override
        protected boolean isHeldExclusively() {
            return true;
        }

        Condition newCondition() { return new ConditionObject(); }
    }

    @Override
    public void lock() {
        sync.acquireShared(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return sync.tryAcquireShared(1) >= 0;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        sync.releaseShared(1);
    }

    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }

    public static void main(String[] args) {
        TwiceLock lock = new TwiceLock();
        ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

        for (int i = 0; i < 5; i++) {
            final int index = i;
            threadPool.execute(() -> {
                lock.lock();
                try {
                    Thread thread = Thread.currentThread();
                    System.out.println(index + "开始");
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(index + "结束");
                } finally {
                    lock.unlock();
                }
            });
        }
    }
}
